package com.sise.bl.dao.impl;

import com.sise.bl.dao.ProductDao;
import com.sise.bl.entity.Product;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository(value = "productDao")
@SuppressWarnings("all")
public class ProductDaoImpl extends BaseDaoImpl<Product> implements ProductDao {

    @Override
    public Long selectCountByTid(Integer tid) {
        String sql = "select count(1) from Product where t_id = :tid";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tid", tid);
        Long count = count(sql, params);
        return count;
    }

    @Override
    public List<Product> selectProductByPage(int page, int pageSize, Integer tid) {
        String sql = "select p from Product p join Type t on p.type.tid=t.tid where t.tid=?0 ";
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("tid", tid);
        Query query = this.getCurrentSession().createQuery(sql);
        query.setParameter(0, tid);
        List<Product> products = query.setFirstResult((page - 1) * pageSize).setMaxResults(pageSize).list();
//        List<Product> products = find(sql, params, (page - 1) * pageSize, pageSize);
        return products;
    }

    @Override
    public Product selectProductByPid(Integer pid) {
        return get(Integer.valueOf(pid));
    }

    @Override
    public int addProduct(Product product) {
        int save = (int) save(product);
        return save;
    }

    @Override
    public List<Product> selectAll() {
        String sql = "from Product";
        List<Product> products = find(sql);
        return products;
    }

    @Override
    public List<Product> selectByTid(Integer tid) {
        String sql = "from Product where t_id=:tid";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tid", tid);
        List<Product> products = find(sql, params);
        return products;
    }

    @Override
    public void deleteProduct(Product product) {
        this.getCurrentSession().delete(product);
    }

    @Override
    public void deleteProductByTid(Integer tid) {
        String sql = "delete from Product p where p.type.tid=?0";
        Query query = this.getCurrentSession().createQuery(sql);
        query.setParameter(0, tid);
        query.executeUpdate();
    }

    @Override
    public int updateProduct(Product product) {
        try {
            this.getCurrentSession().update(product);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
